import { api } from '../../utils/api';

Page({
  data: {
    chats: [] as any[],
    currentUser: null as any,
    websocket: null as WechatMiniprogram.SocketTask | null,
  },

  onLoad() {
    this.checkLogin();
    this.loadUserInfo();
    this.loadChatList();
    this.connectWebSocket();
  },

  onShow() {
    this.loadChatList();
  },

  async checkLogin() {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login',
      });
      return;
    }
    api.setToken(token);
  },

  async loadUserInfo() {
    try {
      const res: any = await api.getCurrentUser();
      if (res.success && res.user) {
        this.setData({
          currentUser: res.user,
        });
      }
    } catch (error) {
      console.error('加载用户信息失败:', error);
    }
  },

  async loadChatList() {
    try {
      const res: any = await api.getRecentChats();
      if (res.success && res.messages) {
        // 处理聊天列表数据
        const chatMap = new Map();
        res.messages.forEach((msg: any) => {
          const otherUserId = msg.senderId === this.data.currentUser?.id 
            ? msg.receiverId 
            : msg.senderId;
          
          if (!chatMap.has(otherUserId)) {
            chatMap.set(otherUserId, {
              userId: otherUserId,
              lastMessage: msg,
              unreadCount: 0,
              nickname: `用户${otherUserId}`,
              avatar: '',
            });
          } else {
            const chat = chatMap.get(otherUserId);
            if (new Date(msg.createdAt) > new Date(chat.lastMessage.createdAt)) {
              chat.lastMessage = msg;
            }
          }
        });

        // 获取未读消息数
        const unreadRes: any = await api.getUnreadMessages();
        if (unreadRes.success && unreadRes.messages) {
          unreadRes.messages.forEach((msg: any) => {
            const otherUserId = msg.senderId;
            if (chatMap.has(otherUserId)) {
              chatMap.get(otherUserId).unreadCount++;
            } else {
              chatMap.set(otherUserId, {
                userId: otherUserId,
                lastMessage: msg,
                unreadCount: 1,
                nickname: `用户${otherUserId}`,
                avatar: '',
              });
            }
          });
        }

        // 获取联系人信息填充昵称和头像
        try {
          const contactsRes: any = await api.getContacts();
          if (contactsRes.success && contactsRes.contacts) {
            contactsRes.contacts.forEach((contact: any) => {
              if (chatMap.has(contact.contactId)) {
                const chat = chatMap.get(contact.contactId);
                chat.nickname = contact.nickname || `用户${contact.contactId}`;
                chat.avatar = contact.avatar || '';
              }
            });
          }
        } catch (error) {
          console.error('获取联系人信息失败:', error);
        }

        const chats = Array.from(chatMap.values());
        this.setData({
          chats,
        });
      }
    } catch (error) {
      console.error('加载聊天列表失败:', error);
    }
  },

  connectWebSocket() {
    const token = api.getToken();
    if (!token) return;

    const userId = this.data.currentUser?.id;
    if (!userId) {
      setTimeout(() => this.connectWebSocket(), 1000);
      return;
    }

    const ws = wx.connectSocket({
      url: `ws://localhost:8080/ws/message?userId=${userId}`,
      header: {
        token,
      },
    });

    ws.onOpen(() => {
      console.log('WebSocket连接成功');
    });

    ws.onMessage((res: any) => {
      try {
        const message = JSON.parse(res.data);
        // 更新聊天列表
        this.loadChatList();
      } catch (e) {
        console.error('解析WebSocket消息失败:', e);
      }
    });

    ws.onError((err) => {
      console.error('WebSocket错误:', err);
    });

    ws.onClose(() => {
      console.log('WebSocket连接关闭');
      // 尝试重连
      setTimeout(() => this.connectWebSocket(), 3000);
    });

    this.setData({
      websocket: ws,
    });
  },

  onChatItemTap(e: any) {
    const userId = e.currentTarget.dataset.userid;
    wx.navigateTo({
      url: `/pages/chat-detail/chat-detail?userId=${userId}`,
    });
  },

  onContactsTap() {
    wx.navigateTo({
      url: '/pages/contacts/contacts',
    });
  },

  onMyQRCodeTap() {
    wx.navigateTo({
      url: '/pages/qrcode/qrcode',
    });
  },

  onUnload() {
    if (this.data.websocket) {
      this.data.websocket.close();
    }
  },

  formatTime(timestamp: any) {
    if (!timestamp) return '';
    
    // 处理字符串格式 "yyyy-MM-dd HH:mm:ss" 或 ISO 格式
    let date: Date;
    if (typeof timestamp === 'string') {
      // 如果包含空格，说明是 "yyyy-MM-dd HH:mm:ss" 格式
      if (timestamp.includes(' ')) {
        // 将 "yyyy-MM-dd HH:mm:ss" 转换为标准格式
        date = new Date(timestamp.replace(' ', 'T') + ':00');
      } else {
        date = new Date(timestamp);
      }
    } else {
      date = new Date(timestamp);
    }
    
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      return '';
    }
    
    const now = new Date();
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const msgDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
    const diff = today.getTime() - msgDate.getTime();
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    const hours = date.getHours();
    const minutes = date.getMinutes();
    const timeStr = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
    
    if (days === 0) {
      return timeStr;
    } else if (days === 1) {
      return '昨天 ' + timeStr;
    } else if (days < 7) {
      const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
      return `周${weekDays[date.getDay()]} ${timeStr}`;
    } else {
      const month = date.getMonth() + 1;
      const day = date.getDate();
      return `${month}/${day} ${timeStr}`;
    }
  },

  getMessagePreview(message: any) {
    if (!message) return '[消息]';
    const type = message.messageType;
    switch (type) {
      case 'TEXT':
        return message.content || '[消息]';
      case 'VOICE':
        return `[语音] ${message.voiceDuration || 0}''`;
      case 'IMAGE':
        return '[图片]';
      case 'LOCATION':
        return '[位置]';
      default:
        return '[消息]';
    }
  },
});

